﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.IO;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.Geoprocessor;
using System.Configuration;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;

namespace WindowsApplication1
{
    public partial class 数据导入 : Form
    {
        public 数据导入()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                try{
    
                    conn1.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\r\n" + "打开主数据库失败!");
                    return;
                }
                string[] urls = textBox1.Text.Split(';');
                string errorurls = "";
                foreach (string url in urls)
                {
                    try
                    {
                        string fromconnstr = "Data Source=(DESCRIPTION =    (ADDRESS = (PROTOCOL = TCP)(HOST = {0})(PORT = 1521))    (CONNECT_DATA =      (SERVER = DEDICATED)      (SERVICE_NAME = orcl)    )  );User ID={1};Password={2}";
                        fromconnstr = string.Format(fromconnstr, url, textBox2.Text, textBox3.Text);
                        DbConnection conn2 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, fromconnstr);
                        try
                        {
                            conn2.Open();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + "\r\n" + "打开" + textBox1.Text + "数据库失败!");
                            continue;
                        }
                        DbCommand command2 = conn2.CreateCommand();
                        command2.CommandText = "select distinct communitid from 社区";
                        DbDataReader reader = command2.ExecuteReader();
                        string communitids = "";
                        while (reader.Read())
                        {
                            communitids += "'" + reader.GetString(0) + "',";
                        }
                        communitids = "(" + communitids.TrimEnd(',') + ")";
                        reader.Close();
                        conn2.Close();
                        //DbCommand command1 = conn1.CreateCommand();
                        //command1.CommandText = "delete from 建筑 where substr(buildingid,0,12) in " + communitids;
                        //command1.ExecuteNonQuery();
                        //command1.CommandText = "delete from 用电建筑 where substr(建筑统一编码,0,12) in " + communitids;
                        //command1.ExecuteNonQuery();
                        //command1.CommandText = "delete from 用电建筑信息 where substr(建筑统一编码,0,12) in " + communitids;
                        //command1.ExecuteNonQuery();
                        IWorkspaceFactory fac = new SdeWorkspaceFactoryClass() as IWorkspaceFactory;
                        IPropertySet pset = new PropertySetClass();
                        pset.SetProperty("Server", url);
                        pset.SetProperty("Instance", "5151");
                        pset.SetProperty("user", textBox2.Text);
                        pset.SetProperty("password", textBox3.Text);
                        pset.SetProperty("Database", "");
                        pset.SetProperty("version", "sde.DEFAULT");
                        string folder = @"c:\";
                        string filename = @"ddd1.sde";
                        if (System.IO.File.Exists(folder + filename))
                        {
                            try
                            {
                                System.IO.File.Delete(folder + filename);
                            }
                            catch { }
                        }
                        fac.Create(folder, filename, pset, 0);
                        string folder1 = "c:\\";
                        string filename1 = "aaa1.sde";
                        if (System.IO.File.Exists(folder1 + filename1))
                        {
                            System.IO.File.Delete(folder1 + filename1);
                        }
                        fac = ((IDataset)Form1.建筑图层.FeatureClass).Workspace.WorkspaceFactory;
                        fac.Create(folder1, filename1, ((IDataset)Form1.建筑图层.FeatureClass).Workspace.ConnectionProperties, 0);
                        Geoprocessor pro = new Geoprocessor();
                        
                        MakeFeatureLayer makeflayer = new MakeFeatureLayer(folder1 + filename1 + "\\" + Settings.建筑图层,Settings.建筑图层);
                        makeflayer.where_clause = "substr(buildingid,0,12) in " + communitids;
                        pro.Execute(makeflayer,null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        DeleteFeatures delfeatures = new DeleteFeatures(Settings.建筑图层);
                        pro.Execute(delfeatures,null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        Append append = new Append();
                        append.inputs = folder + filename + "\\建筑";
                        append.target = folder1 + filename1 + "\\建筑";
                        pro.Execute(append,null);
                        textBox4.Text = "";
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        makeflayer = new MakeFeatureLayer(folder1 + filename1 + "\\" + Settings.用电建筑图层, Settings.用电建筑图层);
                        makeflayer.where_clause = "substr(建筑统一编码,0,12) in " + communitids;
                        pro.Execute(makeflayer, null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        delfeatures = new DeleteFeatures(Settings.用电建筑图层);
                        pro.Execute(delfeatures,null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        append = new Append();
                        append.inputs = folder + filename + "\\用电建筑";
                        append.target = folder1 + filename1 + "\\用电建筑";
                        pro = new Geoprocessor();
                        pro.Execute(append, null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        MakeTableView makeview = new MakeTableView(folder1 + filename1 + "\\" + Settings.用电建筑信息, Settings.用电建筑信息);
                        makeview.where_clause = "substr(建筑统一编码,0,12) in " + communitids;
                        pro.Execute(makeview, null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        DeleteRows delrows = new DeleteRows(Settings.用电建筑信息);
                        pro.Execute(delrows,null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }
                        append.inputs = folder + filename + "\\用电建筑信息";
                        append.target = folder1 + filename1 + "\\用电建筑信息";
                        pro.Execute(append, null);
                        for (int i = 0; i < pro.MessageCount; i++)
                        {
                            string message = pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                            if (message.ToLower().Contains("error"))
                            {
                                errorurls += url + ";";
                            }
                            textBox4.Text += message;
                            textBox4.Text += "\r\n";
                        }

                    }
                    catch (Exception ex)
                    {
                        errorurls += url + ";";
                        File.AppendAllText("log.txt",ex.Message + "\r\n" + ex.StackTrace + "\r\n");
                    }
                }
                if (errorurls != "")
                {
                    MessageBox.Show(errorurls + "的数据未能成功导入主数据库");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                File.AppendAllText("log.txt", ex.Message + "\r\n" + ex.StackTrace);
            }
            MessageBox.Show("数据导入结束");
        }
    }
}
